import fetch from "node-fetch"
import { HttpProxyAgent } from 'http-proxy-agent'
import { API_KEY, PROXY_PORT, PROXY_PORT, PROXY_URL, OPENAI_URL } from '../config/index.js'

const proxyUrl = `${PROXY_URL}:${PROXY_PORT}`
const agent = new HttpProxyAgent(proxyUrl)

export const useFetchToOpenAIGPT = (prompt, onProgress, finishEnd) => {
  // fetch请求，格式可以看 openai官网：
  fetch(
    OPENAI_URL,
    {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content:  prompt}],
        stream: true
      }),
      agent
    },
  ).then(res => {
    res.body.on('data', chunk => {
      const payloads = chunk.toString().split('\n\n')
      for(const payload of payloads) {
        if(payload.includes('[DONE]')) return
        if(payload.startsWith('data: ')) {
          const data = JSON.parse(payload.replace('data: ', ''))
          try {
            const chunk = data.choices[0]?.delta?.content
            if(chunk) {
              // console.log(chunk)
              onProgress(chunk)
            }
          } catch (err) {
            console.error('Error with json parse ', err)
            finishEnd()
          }
        }
      }
    })
  }).catch(err => {
    console.error('报错：', err)
    finishEnd()
  })
  
}






